import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

//检查并写入
public class PutDemo3 {
    static Configuration conf = null;

    static {
        conf = HBaseConfiguration.create();
        conf.set("hbase.rootdir", "hdfs://192.168.126.139:9000/hbase");
        conf.set("hbase.master", "hdfs://192.168.126.139:60010");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        conf.set("hbase.zookeeper.quorum", "192.168.126.139");
    }

    public static void checkAndPut(String tableName, String row, String family, String column, String value) {
        try {
            HBaseAdmin admin = new HBaseAdmin(conf);
            if (!admin.tableExists(Bytes.toBytes(tableName))) {
                System.err.println("表" + tableName + "不存在");
                System.exit(1);
            }
            HTable table = new HTable(conf, TableName.valueOf(tableName));
            Put put = new Put(Bytes.toBytes(row));
            put.add(Bytes.toBytes(family), Bytes.toBytes(column), Bytes.toBytes(value));
            table.checkAndPut(Bytes.toBytes(row), Bytes.toBytes(family), Bytes.toBytes(column), null, put);
            table.flushCommits();
            System.out.println("插入成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
        checkAndPut("stu", "row003", "info", "name", "lisi");
        checkAndPut("stu", "row003", "grade", "C++", "75");

    }
}
